﻿using mozhi.smarterp.BasicData.Suppliers.Repositories;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;

namespace mozhi.smarterp.BasicData.Suppliers.Services
{
    public class SupplierManager : DomainService
    {
        private ISupplierRepository _repository;

        public SupplierManager(ISupplierRepository repository)
        {
            _repository = repository;
        }

        public async Task<Supplier> CreateAsync(Guid id, string code, string name, bool activated)
        {
            var matchCount = await _repository.GetCountAsync(code, null, null) + await _repository.GetCountAsync(null, name, null);

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            var supplier = new Supplier(id, code, name, activated);

            return supplier;
        }

        public async Task<Supplier> UpdateAsync(Guid id, string code, string name, bool activated)
        {
            var supplier = await _repository.GetAsync(id);

            if (supplier == null)
                throw new BusinessException($"供应商：{id}不存在", "100000");

            var matchCount = await _repository.GetCountAsync(code, null, id) + await _repository.GetCountAsync(null, name, id);

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            supplier.Change(code, name, activated);

            return supplier;
        }
    }
}
